package com.atguigu.yygh.hosp.controller.api;

import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.hosp.service.HosptialService;
import com.atguigu.yygh.hosp.utils.HttpRequestHelper;
import com.atguigu.yygh.hosp.utils.MD5;
import com.atguigu.yygh.model.hosp.HospitalSet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/*==========================================
      时 间:   2022-03-07
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@RequestMapping("/api/hosp")
@RestController
public class ApiHospitalController {

    @Autowired
    private HosptialService hosptialService;
    @Autowired
    private HospitalSetService hospitalSetService;


    @PostMapping("/hospital/show")
    public R getHospitalInfo(HttpServletRequest httpServletRequest){
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(httpServletRequest.getParameterMap());
        //TODO: 校验
       String hoscode= (String)paramMap.get("hoscode");
       Map<String,Object> map=hosptialService.getHospitalByHoscode(hoscode);
        return R.ok().code(200).data(map);
    }

    @PostMapping("/saveHospital")
    public R saveHospital(HttpServletRequest httpServletRequest){
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(httpServletRequest.getParameterMap());
        String sign = (String)paramMap.get("sign");
        //TODO 响应码应该是200:sign
        String hoscode = (String)paramMap.get("hoscode");
        QueryWrapper<HospitalSet> queryWrapper=new QueryWrapper<HospitalSet>();
        queryWrapper.eq("hoscode",hoscode);
        HospitalSet one = hospitalSetService.getOne(queryWrapper);
        if(one == null){
            throw new YYGHException(20001,"没有该医院信息");
        }
        String encrypt = MD5.encrypt(one.getSignKey());
        if(!StringUtils.isEmpty(encrypt) && !StringUtils.isEmpty(sign) && sign.equals(encrypt)){
            String logoData= (String)paramMap.get("logoData");
            logoData= logoData.replaceAll(" ", "+");
            paramMap.put("logoData",logoData);
            hosptialService.saveHospital(paramMap);
        }else{
            throw new YYGHException(20001,"校验失败");
        }

        return R.ok().code(200);
    }

}
